package config

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/BurntSushi/toml"
)

type DBConfig struct {
	Host             string `toml:"host" form:"host" json:"host"`
	Port             string `toml:"port" form:"port" json:"port"`
	User             string `toml:"user" form:"user" json:"user"`
	DbName           string `toml:"dbname" form:"dbname" json:"dbName"`
	Password         string `toml:"password" form:"password" json:"password"`
	NeedInit         bool   `toml:"need_init" form:"needInit" json:"needInit"`
	NeedInitBusiness bool   `toml:"need_init_business" form:"needInitBusiness" json:"needInitBusiness"`
	LogLevel         int    `toml:"log_level" form:"logLevel" json:"logLevel"`
}

var DbConfig *DBConfig

func InitDBConfig() {
	//读取配置文件部分
	filePath, err := filepath.Abs("./config/db_config.toml")
	if err != nil {
		panic(err)
	}
	if _, err := toml.DecodeFile(filePath, &DbConfig); err != nil {
		fmt.Println(err.Error())
		panic(errors.New("logger配置文件读取失败"))
	}
}

// Update 更新写入配置文件
func (c *DBConfig) UpdateDbConfig() bool {
	buf := new(bytes.Buffer)
	err := toml.NewEncoder(buf).Encode(c)
	if err != nil {
		fmt.Println(err)
	}
	err = os.WriteFile("./config/db_config.toml", buf.Bytes(), 0777)
	if err != nil {
		fmt.Println("配置文件写入失败", err.Error())
		return false
	}
	return true
}

// EnableNeedInitBusiness 设置是否需要初始化数据库
func (c *DBConfig) EnableNeedInitBusiness() bool {
	if c.NeedInitBusiness {
		return true
	}
	c.NeedInitBusiness = true
	return c.UpdateDbConfig()
}
